﻿using AutoMapper;
using BW.MesProject.Production.Domain;
using BW.MesProject.Production.Domain.Dto.Input;
using BW.MesProject.Production.Domain.Dto.Input.WorkOrder;
using BW.MesProject.Production.Domain.Model;
using BW.MesProject.Production.Infrastructure;
using BW.MesProject.Public.Application.DocCode;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using BW.MesProject.WareHouse.Domain;
using SqlSugar;

namespace BW.MesProject.Production.Application
{
    public class WorkOrderServices : IWorkOrderServices
    {
        private readonly IBaseRepository<WORKORDERMODEL> _baseRepository;
        private readonly IMapper _mapper;
        private readonly IGetDocServices<WORKORDERMODEL> _docServices;
        private readonly IBaseRepository<ProcessItemModel> _processitemRepository;
        private readonly IBaseRepository<WORKPROESSMODEL> _workoProcessRepository;
        private readonly IBaseRepository<ProcessManagModel> _processManagModelRepository;
        public WorkOrderServices(IBaseRepository<WORKORDERMODEL> baseRepository, IMapper mapper, IGetDocServices<WORKORDERMODEL> docServices, IBaseRepository<ProcessItemModel> processitemRepository, IBaseRepository<WORKPROESSMODEL> workoProcessRepository, IBaseRepository<ProcessManagModel> processManagModelRepository)
        {
            _baseRepository = baseRepository;
            _mapper = mapper;
            _docServices = docServices;
            _processitemRepository = processitemRepository;
            _workoProcessRepository = workoProcessRepository;
            _processManagModelRepository = processManagModelRepository;
        }

        public ApiResult<int> CreateWorkOrder(AddWorkOrderInput input)
        {
            // 添加事务处理
            var db = _baseRepository.GetAll().Context;  // 获取SqlSugarClient
            try
            {
                db.Ado.BeginTran();
                WORKORDERMODEL workorder = _mapper.Map<WORKORDERMODEL>(input);
                workorder.CREATETIME = DateTime.Now;
                //var code = "WO" + DateTime.Now.ToString("yyyyMMdd") + new Random().Next(1000, 9999).ToString();
                var code = _docServices.GetDoCode("工单管理");
                workorder.WORKORDERCODE = code;
                workorder.ISDELETED = false;
                workorder.CREATEBY = "admin"; // 这里可以替换为实际的创建用户名
                workorder.CREATETIME = DateTime.Now;
                workorder.SOURCE = "MES";
                workorder.QUANTITYNUM = 0;
                workorder.GOODNUM = 0;
                workorder.FAILNUM = 0;
                workorder.PROGRESS = "0%";
                workorder.COMPLETEDNUM = 0;
                workorder.WORKORDERSTATUS = "初始化";
                workorder.TIME = workorder.WORKSTARTTIME.ToString() + " -- " + workorder.WORKORDERTIME.ToString();
                int r = _baseRepository.Add(workorder);
                var process = _processitemRepository.GetAll().Where(x => x.PRId == input.ROUTINGID).ToList();
                for (int i = 0; i < process.Count(); i++)
                {
                    WORKPROESSMODEL workProcess = new WORKPROESSMODEL()
                    {
                        WORKORDERCODE = workorder.WORKORDERCODE,
                        PMID = process[i].PMId,
                        NONUM = 0,
                        NUM = 0,
                        INDEX = process[i].PNum,
                        ISSTATE = false, // 默认未完成状态
                        SUM = workorder.WORKORDERNUM,
                        ISSTART = false,
                        PRODUCTIONLINEID = workorder.PRODUCTIONLINEID,
                        STARTETIME = workorder.WORKSTARTTIME,
                        ENDTIME = workorder.WORKORDERTIME,
                    };
                    workProcess.PMNAME = _processManagModelRepository.GetValue(x => x.PMId == workProcess.PMID).PMName;
                    
                    if (process[i].PNum == 1)
                    {
                        workProcess.ISSHOW = true;
                    }
                    else
                    {
                        workProcess.ISSHOW = false;
                    }
                    _workoProcessRepository.Add(workProcess);
                }
                db.Ado.CommitTran();
                if (r > 0)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Success,
                        Message = "工单创建成功",
                        Data = r
                    };
                }
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Error,
                    Message = "工单创建失败",
                    Data = r
                };
                
            }
            catch (Exception ex)
            {
                db.Ado.RollbackTran();
                throw ex;
            }
           
        }

        public ApiResult<int> DeleteWorkOrder(int Id)
        {
            WORKORDERMODEL workorder = _baseRepository.GetValue(x => x.WORKORDERID == Id);
            if (workorder==null)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "工单不存在",
                    Data = 0
                };
            }
            int r = _baseRepository.Delete(workorder);
            if (r > 0)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "工单删除成功",
                    Data = r
                };
            }
            return new ApiResult<int>()
            {
                Code = ApiEnums.Error,
                Message = "工单删除失败",
                Data = r
            };
        }

        public ApiResult<WORKORDERMODEL> GetWorkOrder(int Id)
        {
            WORKORDERMODEL workorder = _baseRepository.GetValue(x => x.WORKORDERID == Id);
            if (workorder == null)
            {
                return new ApiResult<WORKORDERMODEL>()
                {
                    Code = ApiEnums.Fail,
                    Message = "工单不存在",
                    Data = null
                };
            }
            return new ApiResult<WORKORDERMODEL>()
            {
                Code = ApiEnums.Success,
                Message = "工单获取成功",
                Data = workorder
            };
        }

        public ApiResult<List<WORKORDERMODEL>> GetWorkOrders(PageInput input)
        {
            ISugarQueryable<WORKORDERMODEL> workorders = _baseRepository.GetAll();

            if(workorders==null)
            {
                return new ApiResult<List<WORKORDERMODEL>>()
                {
                    TotalCount = workorders.Count(),
                    Data = new List<WORKORDERMODEL>(),
                    Message = "工单列表获取失败",
                    Code = ApiEnums.Fail
                };
            }
            
            if(input.PageIndex!=0&&input.PageSize!=0)
            {
                return new ApiResult<List<WORKORDERMODEL>>()
                {
                    TotalCount = workorders.Count(),
                    Data = workorders.ToPageList(input.PageIndex, input.PageSize), // 假设每页10条数据，实际分页参数可以根据需求调整
                    Message = "工单列表获取成功",
                    Code = ApiEnums.Success
                };
            }

            return new ApiResult<List<WORKORDERMODEL>>()
            {
                Data = workorders.ToList(), // 假设每页10条数据，实际分页参数可以根据需求调整
                Message = "工单列表获取成功",
                TotalCount = workorders.Count(),
                Code = ApiEnums.Success
            };
        }

        public ApiResult<List<WORKORDERMODEL>> GetStartWorkOrders(PageInput input)
        {
            ISugarQueryable<WORKORDERMODEL> workorders = _baseRepository.GetAll().Where(x=>x.WORKORDERSTATUS!="初始化");

            if (input.PageIndex != 0 && input.PageSize != 0)
            {
                return new ApiResult<List<WORKORDERMODEL>>()
                {
                    TotalCount = workorders.Count(),
                    Data = workorders.ToPageList(input.PageIndex, input.PageSize), // 假设每页10条数据，实际分页参数可以根据需求调整
                    Message = "工单列表获取成功",
                    Code = ApiEnums.Success
                };
            }

            return new ApiResult<List<WORKORDERMODEL>>()
            {
                Data = workorders.ToList(), // 假设每页10条数据，实际分页参数可以根据需求调整
                Message = "工单列表获取成功",
                TotalCount = workorders.Count(),
                Code = ApiEnums.Success
            };
        }

        public ApiResult<int> SplitWorkOrder(SplitWorkOrderInput input)
        {
            WORKORDERMODEL workorder = _baseRepository.GetAll().First(x => x.WORKORDERCODE == input.WorkOrderCode);
            if(workorder == null)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "工单不存在",
                    Data = 0
                };
            }
            if(workorder.WORKORDERNUM<input.SplitNum)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "工单数量不足，无法拆分",
                    Data = 0
                };
            }
            workorder.WORKORDERNUM -= input.SplitNum;
            _baseRepository.Update(workorder);
            workorder.WORKORDERCODE = _docServices.GetDoCode("工单管理");
            workorder.WORKORDERNUM = input.SplitNum;
            workorder.WORKSTARTTIME = input.StartTime;
            workorder.WORKORDERTIME = input.EndTime;
            workorder.PRODUCTIONLINEID = input.Productionlineid;
            workorder.WORKORDERREMARK = input.Remark;
            workorder.ISDELETED = false;
            workorder.CREATETIME = DateTime.Now;
            workorder.CREATEBY = "admin"; // 这里可以替换为实际的创建用户名
            workorder.TICKETNUMBER = input.WorkOrderCode; // 关联原工单的工单号
            workorder.TIME = workorder.WORKSTARTTIME.ToString() + " -- " + workorder.WORKORDERTIME.ToString();
            int r = 0;
            r = _baseRepository.Add(workorder);
            if (r > 0)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "工单拆分成功",
                    Data = r
                };
            }
            return new ApiResult<int>()
            {
                Code = ApiEnums.Error,
                Message = "工单拆分失败",
                Data = r
            };
        }

        public ApiResult<int> UpdateWorkOrder(UpdateWorkorderInput workorder)
        {
            WORKORDERMODEL uworkorder = _baseRepository.GetValue(x => x.WORKORDERID == workorder.WORKORDERID);
            uworkorder = _mapper.Map(workorder, uworkorder);
            uworkorder.UPDATETIME = DateTime.Now;
            uworkorder.UPDATEBY = "admin"; // 这里可以替换为实际的更新用户名
            uworkorder.TIME = uworkorder.WORKSTARTTIME.ToString() + " -- " + uworkorder.WORKORDERTIME.ToString();

            int r = _baseRepository.Update(uworkorder);
            if(r > 0)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "工单更新成功",
                    Data = r
                };
            }
            return new ApiResult<int>()
            {
                Code = ApiEnums.Error,
                Message = "工单更新失败",
                Data = r
            };
        }

        public ApiResult<int> StartWorkOrder(string WorkOrderCode)
        {
            var workorder = _baseRepository.GetAll().First(x=>x.WORKORDERCODE == WorkOrderCode);
            workorder.WORKORDERSTATUS = "已开工";
            int r = _baseRepository.Update(workorder);
            if(r>0)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "工单已下发",
                    Data = r
                };
            }
            else
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Error,
                    Message = "工单下发失败",
                    Data = r
                };
            }
        }
    }
}
